package com.c.ctgproject.ui.login

import android.os.Handler
import android.widget.Button
import android.widget.LinearLayout
import com.c.ctgproject.R
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.entity.CharacterMenuEntity
import com.c.ctgproject.entity.LoginEntity
import com.c.ctgproject.entity.MenusEntity
import com.c.ctgproject.mode.MyConstants
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserver
import com.c.ctgproject.http.ObserverListener
import com.c.ctgproject.retrofit.Constants
import com.c.ctgproject.ui.collect.CollectCarHomeActivity
import com.c.ctgproject.utils.*
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_characters_change.*
import okhttp3.ResponseBody
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textColorResource
import java.util.ArrayList

/**
 *作者:LiBW
 *创建日期: 2020/8/19
 *描述: 角色切换 页面  身份选择 页面
 */
class CharactersChangeActivity : BaseActivity() {

    override fun getLayout() = R.layout.activity_characters_change

    override fun event() {


        changeTransparentStatusBar()
        val userInfo = intent.getStringExtra(MyConstants.USER_INFO)
        if (userInfo == null) {
            CustomToast.showToast(this, "账号信息有误请重新登录")
            startActivity<LoginActivity>()
            finish()
        }
        val userEntity = Gson().fromJson(userInfo, LoginEntity::class.java).data

        //缓存的上次用户登录的角色
        val characterId = sharedGet(MyConstants.CHARACTER_ID, "0") as String
        if (characterId.isNotEmpty() && characterId != "0") {
            getMenu(characterId)
        }

        mCharacterContainLL.removeAllViews()
        //遍历用户角色后添加到列表里
//        userEntity?.roles?.let { list ->
//            list.forEach {
//                val button = Button(this)
//                button.text = it.name
//                button.tag = it.id
//                button.textColorResource = R.color.white
//                button.backgroundResource = R.drawable.bg_btn_green_radius
//                val param = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 40f.toPx(this))
//                param.topMargin = 10f.toPx(this)
//                param.bottomMargin = 10f.toPx(this)
//                param.marginStart = 10f.toPx(this)
//                param.marginEnd = 10f.toPx(this)
//                button.layoutParams = param
//                mCharacterContainLL.addView(button)
//            }
//        }
        if (mCharacterContainLL.childCount == 0) {
            showToast("该账户下没有角色")
            //TODO 临时进进
            startActivity<CollectCarHomeActivity>()
//            Utils.setShare2(applicationContext, "loginstatu", "1")
//            //清除所有sp缓存 进入登录页面
//            getSharedPreferences("ShareData", 0).edit().clear().apply()
//            userToken = ""
//            startActivity<LoginActivity>()
//            finish()
        }
    }

    override fun click() {
        //角色点击事件
        val buttonCount = mCharacterContainLL.childCount
        repeat(buttonCount) {
            mCharacterContainLL.getChildAt(it).setOnClickListener { button ->
                val characterId = (button as Button).tag
                getMenu(characterId.handlerNull())
            }
        }
    }

    //获取菜单
    private fun getMenu(characterId: String) {
        //将本次选择的角色ID缓存
        characterId.sharedSave(MyConstants.CHARACTER_ID)

        val characterListener = object : ObserverListener {
            override fun onNext(t: ResponseBody) {
                val result = t.string().handlerNull()
                MyLog.d("角色切换获得目录信息:$result")
                val entity = Gson().fromJson(result, CharacterMenuEntity::class.java)
                if (entity.status == 0) {
                    var menuCode = ""
                    //遍历所有菜单得到parentID为0的,其menuCode为角色flag
                    val menusEntityList = ArrayList<MenusEntity>()
                    entity.data?.menus?.forEach {
                        //将所有的子菜单放入list传给Activity去做判断展示那些子item
                        val menu = MenusEntity()
                        menu.menuCode = it.menuCode
                        menu.menuName = it.menuName
                        menusEntityList.add(menu)
                        //获取父菜单的menuCode
                        val code = getParentMenuCode(it.menuCode)
                        if (code.isNotEmpty()) {
                            menuCode = code
                        }
                    }
                    //多角色下根据子菜单判断父菜单
                    if (menuCode.isNotEmpty()) {
                        characterJump(menuCode, menusEntityList)
                    } else {
                        showToast("该角色暂未开放")
                    }

                } else {
                    //角色选择错误直接回到登录页面
                    val shared = getSharedPreferences("ShareData", 0).edit()
                    shared.clear().apply()
                    showToast(entity.msg.handlerNull())
                    userToken = ""
                    "".sharedSave(Constants.TOKEN)
                    Handler().postDelayed({
                        startActivity<LoginActivity>()
                        finish()
                    }, 1000)
                }
            }

            override fun onError(error: String) {
                showToast(error)
                userToken = ""
                "".sharedSave(Constants.TOKEN)
                startActivity<LoginActivity>()
                finish()
            }
        }
        //调取接口获取菜单
        ApiMethods.charactersChange(MyObserver(this, characterListener), characterId.toInt())
    }


    override fun onBackPressed() {
        exitApp()
    }
}